package com.wzy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.wzy.reggie.common.BaseContext;
import com.wzy.reggie.common.R;
import com.wzy.reggie.dto.OrderDto;
import com.wzy.reggie.entity.*;
import com.wzy.reggie.service.OrderDetailService;
import com.wzy.reggie.service.OrderService;
import com.wzy.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.pkcs11.P11TlsMasterSecretGenerator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("orders:{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 移动端用户查看订单
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userOrderList(int page,int pageSize){
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> dtoPage = new Page<>(page, pageSize);
        //根据用户id查询订单
        Long userId = BaseContext.getCurrentId();//userID
        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId);
        queryWrapper.orderByDesc(Orders::getOrderTime);//按照下单时间降序排序
        orderService.page(pageInfo,queryWrapper);//查出用户所有订单
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> dtoList =records.stream().map((item)->{
            OrderDto orderDto = new OrderDto();
            //将item除了orderDetails和sumNum以外的属性拷贝到orderDto
            BeanUtils.copyProperties(item,orderDto);
            Long orderId = item.getId();//订单编号
            //根据订单编号查询出相应的订单详情信息
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderDto.setOrderDetails(orderDetailList);//将订单中每个订单详情信息就加入orderDto
            //现在要根据orderDetailsList计算出商品总数 需要遍历orderDetailsList
            int sumNum = 0;
            for (OrderDetail orderDetail : orderDetailList) {
               sumNum += orderDetail.getNumber();
            }
            orderDto.setSumNum(sumNum);

            return orderDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }

    @GetMapping("/page")
    public R<Page> orderList(int page, int pageSize, Long number, String beginTime,String endTime){
        //前端传来的时间是字符串，需要转成Date
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrderDto> dtoPage = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        //1.按订单号模糊查询
        queryWrapper.like(number!=null,Orders::getId,number);
        //2.大于beginTime
        if(beginTime!=null){
             LocalDateTime begin_Time = LocalDateTime.parse(beginTime, fmt);
             queryWrapper.gt(Orders::getOrderTime,begin_Time);
         }
        //3.小于endTime
        if(endTime!=null){
            LocalDateTime end_Time = LocalDateTime.parse(endTime, fmt);
            queryWrapper.lt(Orders::getOrderTime,end_Time);
        }
        //4.按订单时间降序排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> dtoList = records.stream().map((item)->{
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item,orderDto);
            Long userId = item.getUserId();
            //根据订单中的useId去用户表查询用户名字
            User user = userService.getById(userId);
            String name = user.getName();//用户姓名
            orderDto.setUserName(name);
            return orderDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }
    @PutMapping
    public R<String> editStatus(@RequestBody Orders orders){
        //获取订单的id
        Long id = orders.getId();
        Orders order = orderService.getById(id);
        order.setStatus(orders.getStatus());
        boolean update = orderService.updateById(order);
        if(update){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }
}
